<template>
  <div class="cart-page">
    <div class="container py-4">
      <!-- 加载中 -->
      <div v-if="loading" class="text-center py-5">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">加载中...</span>
        </div>
        <div class="mt-2">加载中...</div>
      </div>

      <!-- 购物车不为空 -->
      <div v-else-if="cartItems.length > 0">
        <!-- 购物车提示信息 -->
        <div class="cart-notice mb-4" v-if="freeShippingThreshold > 0">
          <div class="alert alert-info d-flex align-items-center">
            <i class="fas fa-truck me-2"></i>
            <span v-if="totalAmount >= freeShippingThreshold">
              恭喜您已享受免费配送服务！
            </span>
            <span v-else>
              再购买 <strong>{{ formatPrice(freeShippingThreshold - totalAmount) }}</strong> 即可享受免费配送
            </span>
          </div>
        </div>

        <div class="row">
          <!-- 左侧：购物车商品列表 -->
          <div class="col-lg-9">
            <!-- 购物车表格 -->
            <div class="cart-table-container">
              <div class="table-responsive">
                <table class="table">
                  <thead class="cart-header">
                  <tr>
                    <th width="50">
                      <div class="form-check">
                        <input
                          type="checkbox"
                          class="form-check-input"
                          v-model="selectAll"
                          @change="toggleSelectAll"
                        >
                      </div>
                    </th>
                    <th>商品信息</th>
                    <th width="120">单价</th>
                    <th width="150">数量</th>
                    <th width="120">小计</th>
                    <th width="100">操作</th>
                  </tr>
                  </thead>
                  <tbody>
                  <tr
                    v-for="item in cartItems"
                    :key="item.id"
                    class="cart-item"
                  >
                    <!-- 选择框 -->
                    <td>
                      <div class="form-check">
                        <input
                          type="checkbox"
                          class="form-check-input"
                          v-model="item.selected"
                          @change="updateSelection"
                        >
                      </div>
                    </td>

                    <!-- 商品信息 -->
                    <td>
                      <div class="d-flex align-items-center">
                        <div class="item-image me-3">
                          <img
                            :src="item.product?.thumbnail || placeholderImage(80, 80)"
                            :alt="item.product?.name || '商品图片'"
                            @error="(event) => { if (event.target) (event.target as HTMLImageElement).src = placeholderImage(80, 80) }"
                          />
                        </div>
                        <div class="item-info">
                          <h6 class="item-name mb-1">
                            <router-link
                              :to="`/products/${item.productId}`"
                              class="text-decoration-none text-dark"
                            >
                              {{ item.product?.name || '商品名称' }}
                            </router-link>
                          </h6>
                          <p class="item-desc text-muted small mb-0">
                            {{ item.product?.description || '暂无描述' }}
                          </p>
                          <div class="item-tags mt-1">
                            <span v-if="item.product?.isHot" class="badge bg-danger me-1">热门</span>
                            <span v-if="item.product?.stock && item.product.stock <= 10"
                                  class="badge bg-warning">库存紧张</span>
                          </div>
                        </div>
                      </div>
                    </td>

                    <!-- 单价 -->
                    <td>
                      <div class="price-info">
                          <span class="current-price text-danger fw-bold">
                            {{ formatPrice(item.product?.price || 0) }}
                          </span>
                      </div>
                    </td>

                    <!-- 数量控制 -->
                    <td>
                      <div class="quantity-control d-flex align-items-center">
                        <button
                          type="button"
                          class="btn btn-outline-secondary btn-sm"
                          @click="decreaseQuantity(item)"
                          :disabled="item.quantity <= 1 || updating"
                        >
                          <i class="fas fa-minus"></i>
                        </button>
                        <input
                          type="number"
                          class="form-control form-control-sm mx-2 text-center"
                          style="width: 60px;"
                          v-model.number="item.quantity"
                          @change="updateQuantity(item)"
                          :min="1"
                          :max="item.product?.stock || 999"
                        />
                        <button
                          type="button"
                          class="btn btn-outline-secondary btn-sm"
                          @click="increaseQuantity(item)"
                          :disabled="item.quantity >= (item.product?.stock || 999) || updating"
                        >
                          <i class="fas fa-plus"></i>
                        </button>
                      </div>
                      <div class="stock-info text-muted small mt-1">
                        库存：{{ item.product?.stock || 0 }}件
                      </div>
                    </td>

                    <!-- 小计 -->
                    <td>
                      <div class="subtotal">
                          <span class="fw-bold text-danger">
                            {{ formatPrice((item.product?.price || 0) * item.quantity) }}
                          </span>
                      </div>
                    </td>

                    <!-- 操作 -->
                    <td>
                      <div class="item-actions">
                        <button
                          type="button"
                          class="btn btn-danger btn-lg"
                          @click="removeItems([item])"
                          title="删除"
                        >
                          <i class="fas fa-trash"></i>
                        </button>
                      </div>
                    </td>
                  </tr>
                  </tbody>
                </table>
              </div>
            </div>

            <!-- 批量操作 -->
            <div class="cart-actions mt-3 d-flex justify-content-between align-items-center">
              <div class="batch-actions">
                <button
                  class="btn btn-outline-danger btn-lg me-2"
                  @click="removeSelectedItems"
                  :disabled="selectedItems.length === 0"
                >
                  <i class="fas fa-trash me-1"></i>
                  删除选中商品
                </button>
              </div>
              <div class="continue-shopping">
                <router-link to="/products" class="btn btn-outline-primary">
                  <i class="fas fa-arrow-left me-1"></i>
                  继续购物
                </router-link>
              </div>
            </div>
          </div>

          <!-- 右侧：订单摘要 -->
          <div class="col-lg-3">
            <div class="order-summary card position-sticky">
              <div class="card-header">
                <h5 class="mb-0">订单摘要</h5>
              </div>
              <div class="card-body">


                <!-- 价格详情 -->
                <div class="price-details">
                  <div class="price-row d-flex justify-content-between mb-2">
                    <span>商品总价 ({{ selectedItems.length }}件)</span>
                    <span>{{ formatPrice(itemsTotal) }}</span>
                  </div>

                  <div class="price-row d-flex justify-content-between mb-3">
                    <span>运费</span>
                    <span v-if="shippingFee === 0" class="text-success">免费</span>
                    <span v-else>{{ formatPrice(shippingFee) }}</span>
                  </div>
                  <hr>
                  <div class="total-price d-flex justify-content-between align-items-center mb-3">
                    <span class="h6 mb-0">应付总额</span>
                    <span class="h5 mb-0 text-danger fw-bold">{{ formatPrice(totalAmount) }}</span>
                  </div>

                  <!-- 结算按钮 -->
                  <button
                    class="btn btn-danger btn-lg w-100"
                    @click="proceedToCheckout"
                    :disabled="selectedItems.length === 0"
                  >
                    <i class="fas fa-credit-card me-2"></i>
                    立即结算 ({{ selectedItems.length }})
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 购物车为空 -->
      <div v-else class="empty-cart text-center py-5">
        <h3 class="mb-3">购物车是空的</h3>
        <p class="text-muted mb-4">快去挑选喜欢的商品吧</p>
        <router-link to="/products" class="btn btn-primary btn-lg">
          <i class="fas fa-arrow-right me-2"></i>
          立即购物
        </router-link>
      </div>
    </div>


  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { Message } from '@/utils/message'
import type { CartItem } from '@/types/cart'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 占位符图片生成函数
const placeholderImage = (width: number, height: number) => {
  return `https://picsum.photos/${width}/${height}?random=${Math.floor(Math.random() * 1000)}`
}

// 页面状态
const loading = ref(false)
const updating = ref(false)
const selectAll = ref(false)


// 配送相关
const freeShippingThreshold = ref(99) // 免费配送门槛

// 购物车选择状态（扩展CartItem类型）
interface ExtendedCartItem extends CartItem {
  selected: boolean
}

// 购物车数据
const cartItems = ref<ExtendedCartItem[]>([])


// 推荐商品
const recommendedProducts = ref<any[]>([])

// 最近浏览
const recentViewed = ref<any[]>([])

// 删除相关
const itemsToRemove = ref<ExtendedCartItem[]>([])

// 计算属性
const selectedItems = computed(() => {
  return cartItems.value.filter(item => item.selected)
})

const itemsTotal = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    const itemTotal = (item.product?.price || 0) * item.quantity
    return total + itemTotal
  }, 0)
})

const discountAmount = computed(() => {
  return 0
})

const shippingFee = computed(() => {
  const subtotal = itemsTotal.value - discountAmount.value
  return subtotal >= freeShippingThreshold.value ? 0 : 10
})

const totalAmount = computed(() => {
  return itemsTotal.value - discountAmount.value + shippingFee.value
})

// 格式化价格
const formatPrice = (price: number | undefined | null) => {
  // 如果价格无效，返回¥0.00
  if (price === undefined || price === null || isNaN(price)) {
    return '¥0.00'
  }
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(price)
}

// 获取购物车数据
const fetchCartData = async () => {
  if (!userStore.isLoggedIn) {
    router.push('/login')
    return
  }

  if (!userStore.userInfo?.id) {
    Message.error('用户信息异常，请重新登录')
    router.push('/login')
    return
  }

  loading.value = true
  try {
    // 使用真实的cartStore获取数据
    await cartStore.fetchCartItems()

    // 将cartStore中的数据转换为带选择状态的数据，并计算价格
    cartItems.value = cartStore.cartItems.map(item => ({
      ...item,
      selected: true, // 默认全选
      price: item.product?.price || 0,
      totalPrice: (item.product?.price || 0) * item.quantity
    }))

    updateSelectAllState()

  } catch (error) {
    console.error('获取购物车数据失败:', error)
    Message.error('获取购物车数据失败')
  } finally {
    loading.value = false
  }
}

const toggleSelectAll = () => {
  cartItems.value.forEach(item => {
    item.selected = selectAll.value
  })
}

const updateSelection = () => {
  updateSelectAllState()
}

const updateSelectAllState = () => {
  selectAll.value = cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
}

const decreaseQuantity = async (item: ExtendedCartItem) => {
  if (item.quantity > 1) {
    item.quantity--
    await updateQuantity(item)
  }
}

const increaseQuantity = async (item: ExtendedCartItem) => {
  if (item.quantity < (item.product?.stock || 999)) {
    item.quantity++
    await updateQuantity(item)
  }
}

const updateQuantity = async (item: ExtendedCartItem) => {
  if (item.quantity < 1) {
    Message.error('商品数量不能少于1')
    return
  }

  updating.value = true
  try {
    // 更新购物车项数量
    await cartStore.updateQuantity(item.id, item.quantity)

    // 更新本地数据
    item.price = item.product?.price || 0
    item.totalPrice = item.price * item.quantity

    Message.success('数量更新成功')
  } catch (error: any) {
    console.error('更新数量失败:', error)
    
    // 显示具体的错误信息
    const errorMessage = error.message || '更新数量失败'
    Message.error(errorMessage)

    // 恢复原来的数量
    await fetchCartData()
  } finally {
    updating.value = false
  }
}



// 删除商品
const removeItems = (items: ExtendedCartItem[]) => {
  itemsToRemove.value = items
  
  // 直接执行删除，不需要模态框确认
  executeRemove()
}

const executeRemove = async () => {
  if (itemsToRemove.value.length === 0) return

  try {
    const idsToRemove = itemsToRemove.value.map(item => item.id)
    console.log('删除购物车项，IDs:', idsToRemove)
    
    await cartStore.removeFromCart(idsToRemove)

    // 重新获取购物车数据以确保同步
    await cartStore.fetchCartItems()
    
    // 更新页面显示的数据
    cartItems.value = cartStore.cartItems.map(item => ({
      ...item,
      selected: true,
      price: item.product?.price || 0,
      totalPrice: (item.product?.price || 0) * item.quantity
    }))

    Message.success('删除成功')
    updateSelectAllState()
  } catch (error: any) {
    console.error('删除失败:', error)
    const errorMessage = error.message || '删除失败'
    Message.error(errorMessage)
  }

  itemsToRemove.value = []
}

const removeSelectedItems = () => {
  const selected = selectedItems.value
  if (selected.length === 0) {
    Message.warning('请选择要删除的商品')
    return
  }

  removeItems(selected)
}




const addToCartFromRecommended = async (product: any) => {
  try {
    await cartStore.addToCart(product.id, 1)
    Message.success('已添加到购物车')

    // 刷新购物车数据
    fetchCartData()
  } catch (error: any) {
    console.error('添加失败:', error)
    const errorMessage = error.message || '添加失败'
    Message.error(errorMessage)
  }
}

const proceedToCheckout = () => {
  if (selectedItems.value.length === 0) {
    Message.warning('请选择要结算的商品')
    return
  }

  // 跳转到结算页面
  router.push({
    path: '/checkout',
    query: {
      items: selectedItems.value.map(item => item.id).join(',')

    }
  })
}

// 监听cartStore的变化
watch(() => cartStore.cartItems, (newItems) => {
  // 当cartStore中的数据变化时，同步更新本地数据
  cartItems.value = newItems.map(item => {
    const existingItem = cartItems.value.find(ci => ci.id === item.id)
    return {
      ...item,
      selected: existingItem?.selected ?? true
    }
  })
  updateSelectAllState()
}, { deep: true })

onMounted(async () => {
  // 确保用户信息完整
  if (userStore.isLoggedIn && !userStore.userInfo) {
    try {
      await userStore.getCurrentUser()
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }
  
  fetchCartData()
})
</script>

<style scoped>
/* 购物车提示 */
.cart-notice .alert {
  border-radius: 10px;
  border: none;
}

/* 购物车表头 */
.cart-header {
  background: #f8f9fa !important;
  border-bottom: 2px solid #e9ecef;
}

/* 购物车项目 */
.cart-item {
  background: white;
  transition: background-color 0.3s ease;
}

.cart-item:hover {
  background: #fafafa;
}

.item-image {
  width: 80px;
  height: 80px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-name {
  font-weight: 500;
  line-height: 1.4;
}

.item-name a {
  color: #333;
}

.item-name a:hover {
  color: #007bff;
}

.item-specs span {
  background: #f8f9fa;
  padding: 2px 8px;
  border-radius: 4px;
  margin-right: 5px;
}

.item-actions .btn {
  min-width: 60px;
  font-size: 14px;
}

/* 数量控制 */
.quantity-controls {
  border: 1px solid #dee2e6;
  border-radius: 6px;
  overflow: hidden;
}

.quantity-controls .btn {
  border: none;
  border-radius: 0;
  width: 30px;
  height: 30px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-controls input {
  border: none;
  border-left: 1px solid #dee2e6;
  border-right: 1px solid #dee2e6;
  border-radius: 0;
  height: 30px;
  padding: 0;
}

.quantity-controls input:focus {
  box-shadow: none;
  border-color: #dee2e6;
}

/* 价格显示 */
.current-price {
  font-size: 1.1rem;
}

.original-price {
  font-size: 0.9rem;
}

.item-total {
  font-size: 1.1rem;
}

/* 订单摘要 */
.order-summary {
  top: 20px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  z-index: 1;
}

.order-summary .card-header {
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}


/* 价格详情 */
.price-row {
  font-size: 14px;
}

.total-price {
  border-top: 2px solid #e9ecef;
  padding-top: 15px;
}

/* 空购物车 */
.empty-cart {
  min-height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 推荐商品 */
.recommended-section .product-card,
.recent-viewed .product-card {
  border: none;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.recommended-section .product-card:hover,
.recent-viewed .product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

.recommended-section .card-img-top,
.recent-viewed .card-img-top {
  height: 120px;
  object-fit: cover;
}

.recommended-section .product-name,
.recent-viewed .product-name {
  font-size: 13px;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.recommended-section .product-name a,
.recent-viewed .product-name a {
  color: #333;
}

.recommended-section .product-name a:hover,
.recent-viewed .product-name a:hover {
  color: #007bff;
}

/* 批量操作 */
.batch-actions .btn {
  font-size: 14px;
}
</style> 